package com.vm.fragment;

import java.io.File;

import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.VolleyError;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.vm.activity.DetailActivity;
import com.vm.commons.CurrentUser;
import com.vm.commons.StringUtil;
import com.vm.commons.VMConst;
import com.vm.db.DownInfoDao;
import com.vm.model.DownInfo;
import com.vm.model.Scene;
import com.vm.model.Soft;
import com.vm.utils.ApkUtils;
import com.vm.utils.DownloadThread;
import com.vm.utils.JsonUtils;
import com.vm.utils.MyDisplayImageOptions;
import com.vm.utils.MyVolley;
import com.wwt.app.R;

public class IntroduceFragment extends BaseFragment {

	protected static final String TAG = "IntroduceFragment";
	private View view;
	RequestQueue mQueue;
	Soft soft;
	TextView tv_software_content;

	Button btn_soft_download;
	ProgressBar progressBar1;

	private int fileSize = 0;
	private int nowProgressValue = 0;
	private DownloadThread downThread;
	private TextView progressText;
	String currentId;
	DownInfoDao dao;
	DownInfo apkInfo;
	Integer isNow;

	/** 标志位，标志已经初始化完成 */
	private boolean isPrepared;
	/** 是否已被加载过一次，第二次就不再去请求数据了 */
	private boolean mHasLoadedOnce;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		Log.i("CategoryGameFragment", "onCreateView");

		if (view == null) {
			view = inflater.inflate(R.layout.software_details, null);
		} else {
			// 缓存的rootView需要判断是否已经被加过parent
			// 如果有parent需要从parent删除
			ViewGroup parent = (ViewGroup) view.getParent();
			if (parent != null) {
				parent.removeView(view);
			}
		}
		return view;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		isPrepared = true;
		lazyLoad();

	}

	/**
	 * 初始化控件
	 */
	private void init() {

		tv_software_content = (TextView) view
				.findViewById(R.id.tv_introduce_content);
		btn_soft_download = (Button) view.findViewById(R.id.btn_soft_download);

		// btn_download_finish = (Button) view
		// .findViewById(R.id.btn_soft_download);
		progressBar1 = (ProgressBar) view.findViewById(R.id.progressBar1);
		progressText = (TextView) view.findViewById(R.id.progressText);

	}

	/**
	 * 
	 */
	// private void initBtn_Intergral() {
	// // 判断是否为积分专区软件
	// if (soft.getTypeId() == 3) {
	// btn_getIntergral.setVisibility(View.GONE);
	// } else {
	// btn_getIntergral.setVisibility(View.VISIBLE);
	// if (CurrentUser.USERID != null) {
	// String url = VMConst.REQUEST_URL + "ifGet?softId="
	// + soft.getId() + "&userId=" + CurrentUser.USERID;
	// StringRequest ifGetRequest = new StringRequest(url,
	// new Listener<String>() {
	//
	// @Override
	// public void onResponse(String response) {
	// if (response.equals("已领取")) {
	// btn_getIntergral.setText("已领取");
	// } else {
	// btn_getIntergral
	// .setOnClickListener(btn_getIntergralListener);
	// }
	// }
	// }, new ErrorListener() {
	//
	// @Override
	// public void onErrorResponse(VolleyError error) {
	// }
	// });
	// mQueue.add(ifGetRequest);
	//
	// // btn_getIntergral.setOnClickListener(btn_getIntergralListener);
	// } else {
	// btn_getIntergral.setOnClickListener(btn_getIntergralListener);
	// // Toast toast = Toast.makeText(DetailActivity.this, "请先登录",
	// // 500);
	// // toast.setGravity(Gravity.CENTER, 0, 0);
	// // toast.show();
	// }
	// }
	//
	// // }
	// }

	/**
	 * 领取积分
	 */
	// OnClickListener btn_getIntergralListener = new OnClickListener() {
	//
	// @Override
	// public void onClick(View v) {
	//
	// if (CurrentUser.USERID != null) {
	// if (progressText.getText().toString().equals("已安装")) {
	// btn_getIntergral.setVisibility(View.VISIBLE);
	// String url = VMConst.REQUEST_URL
	// + "getDownIntergral?softId=" + soft.getId()
	// + "&userId=" + CurrentUser.USERID;
	// StringRequest ifGetRequest = new StringRequest(url,
	// new Listener<String>() {
	//
	// @Override
	// public void onResponse(String response) {
	// if (response.equals("领取成功")) {
	// Toast toast = Toast.makeText(
	// getActivity(), "领取成功", 500);
	// toast.setGravity(Gravity.CENTER, 0, 0);
	// toast.show();
	// btn_getIntergral.setText("已领取");
	// } else {
	// Toast toast = Toast.makeText(
	// getActivity(), response, 500);
	// toast.setGravity(Gravity.CENTER, 0, 0);
	// toast.show();
	// }
	// }
	// }, new ErrorListener() {
	//
	// @Override
	// public void onErrorResponse(VolleyError error) {
	// }
	// });
	// mQueue.add(ifGetRequest);
	//
	// } else {
	// Toast toast = Toast.makeText(getActivity(),
	// "请下载安装,再返回此界面领取积分", 500);
	// toast.setGravity(Gravity.CENTER, 0, 0);
	// toast.show();
	// }
	// } else {
	// Toast toast = Toast.makeText(getActivity(), "请先登录", 500);
	// toast.setGravity(Gravity.CENTER, 0, 0);
	// toast.show();
	// }
	//
	// }
	// };

	private Handler mainHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 500:
				if (nowProgressValue <= fileSize) {

					if (progressText.getText().equals("打开")) {
						progressText.setText("打开");

						Toast toast = Toast
								.makeText(getActivity(), "下载完成", 500);
						toast.setGravity(Gravity.CENTER, 0, 0);
						toast.show();
					} else {
						fileSize = msg.arg1;
						progressBar1.setMax(fileSize);
						new Thread() {
							@Override
							public void run() {
								while (true) {
									progressBar1.setProgress(nowProgressValue);
								}
							}
						}.start();
					}
				} else {
					Toast toast = Toast.makeText(getActivity(), "当前附件已下载", 500);
					toast.setGravity(Gravity.CENTER, 0, 0);
					toast.show();
				}
				break;
			case 600:
				nowProgressValue = msg.arg1;
				if (nowProgressValue <= fileSize) {
					progressText.setTextColor(Color.BLACK);
					// System.out.println("<<<<<<" + fileSize + "<<<"
					// + nowProgressValue);
					double aa = ((double) nowProgressValue / (double) fileSize);
					// System.out.println("<<<<<<<<<"
					// + (Math.round(aa * 100) / 100.0));
					progressText.setText((int) (aa * 100) + "%");

				} else {

				}

				break;
			case 700:
				progressText.setText("下载");
				progressText.setTextColor(Color.BLACK);
				Toast toast = Toast
						.makeText(getActivity(), "网络异常或当前附件不存在", 500);
				toast.setGravity(Gravity.CENTER, 0, 0);
				toast.show();
				break;
			case 800:
				Toast toast1 = Toast.makeText(getActivity(), "URL异常，请联系管理员",
						500);
				toast1.setGravity(Gravity.CENTER, 0, 0);
				toast1.show();
				break;

			case 900:
				Toast toast2 = Toast.makeText(getActivity(), "暂停下载", 500);
				toast2.setGravity(Gravity.CENTER, 0, 0);
				toast2.show();
				break;
			case 1000:
				Toast toast3 = Toast.makeText(getActivity(), "下载完成", 500);
				toast3.setGravity(Gravity.CENTER, 0, 0);
				toast3.show();

				progressText.setText("安装");

				if (progressText.getText().toString().equals("已安装")) {
					// 不做任何操作
				} else if (progressText.getText().toString().equals("安装")) {
					// 执行安装

					progressText.setText("正在安装");

					dao = new DownInfoDao(getActivity());
					dao.complete(currentId);
					File apkfile = new File(StringUtil.getSdApkUrl(soft
							.getName()));
					if (!apkfile.exists()) {
						return;
					}
					Intent i = new Intent(Intent.ACTION_VIEW);

					i.setDataAndType(Uri.parse("file://" + apkfile.toString()),
							"application/vnd.android.package-archive");
					startActivityForResult(i, 12);
				}
				break;
			default:
				break;
			}
			super.handleMessage(msg);
		}
	};

	/**
	 * 下载按钮监听
	 */
	public OnClickListener downClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {

			try {
				if (progressText.getText().toString().equals("已安装")) {
					// 不做任何操作
				} else if (progressText.getText().toString().equals("安装")) {
					// 执行安装
					// Toast toast3 = Toast.makeText(getActivity(), "正在安装",
					// 500);
					// toast3.setGravity(Gravity.CENTER, 0, 0);
					// toast3.show();
					progressText.setText("正在安装");

					File apkfile = new File(StringUtil.getSdApkUrl(soft
							.getName()));
					if (!apkfile.exists()) {
						return;
					}
					Intent i = new Intent(Intent.ACTION_VIEW);

					i.setDataAndType(Uri.parse("file://" + apkfile.toString()),
							"application/vnd.android.package-archive");
					startActivityForResult(i, 12);

				} else if (progressText.getText().toString().equals("正在安装")) {
					return;
				} else {

					// 下载APK
					btn_soft_download.setVisibility(View.GONE);

					progressBar1.setVisibility(View.VISIBLE);
					currentId = v.getTag().toString();
					Log.i(TAG, currentId);
					System.out.println("<<<<" + nowProgressValue + "<<<"
							+ fileSize);
					progressText.setText("稍等");
					progressText.setTextColor(Color.BLACK);
					Message msg = new Message();
					// msg.arg1 = currentId;
					msg.what = 100;
					// 下载地址
					// msg.obj = VMConst.DOWN_URL + currentId + "&userId="
					// + CurrentUser.USERID;
					msg.obj = soft;
					downThread = new DownloadThread(getActivity(), mainHandler);
					downThread.start();

					do {
						downHandler = downThread.getDownHandler();
					} while (null == downHandler);

					downHandler.sendMessage(msg);
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				Log.e(TAG, e.getMessage());
			}

		}
	};

	private Handler downHandler = new Handler();
	Runnable initData = new Runnable() {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			soft = (Soft) getArguments().get("soft");

			// final String softId = getActivity().getIntent()
			// .getStringExtra("softId");
			isNow = getActivity().getIntent().getIntExtra("isNow", 0);
			// currentId = softId;
			// Log.i("currentId", currentId);

			// init();

			/**
			 * 查询当前APK是否正在下载中,如果存在,下载按钮显示继续下载
			 */

			tv_software_content.setText(soft.getIntro());

			btn_soft_download.setTag(soft.getId());
			btn_soft_download.setOnClickListener(downClickListener);

			boolean isInstalled = ApkUtils.isAppInstalled(
					soft.getPackageName(), getActivity());
			// 判断APK是否有安装
			if (isInstalled) {
				progressText.setText("已安装");
			} else {

				File apkfile = new File(Environment
						.getExternalStorageDirectory().getPath()
						+ "/vmclient/"
						+ soft.getName() + ".apk");
				if (apkfile.exists()) {

					// 判断APK在机器的状态,正在下载,已下载,已安装
					dao = new DownInfoDao(getActivity());
					apkInfo = dao.query(currentId);
					if (apkInfo != null) {
						if (apkInfo.getDone() <= apkInfo.getApkLength()) {

							if (apkInfo.getIsPause() == 0) {
								// 继续下载
							} else {
								progressText.setText("继续下载");
							}

						}
					} else {
						progressText.setText("安装");
					}

				}

			}

			if (soft.getSceneList().size() > 0) {
				LinearLayout layout = (LinearLayout) view
						.findViewById(R.id.l_layout_scene);
				layout.removeAllViews();
				// ImageView iv1 =
				// (ImageView)findViewById(R.id.iv_scene1);
				for (int i = 0; i < soft.getSceneList().size(); i++) {

					Scene scene = soft.getSceneList().get(i);
					ImageView imageView = new ImageView(getActivity());

					imageView.setId(i);

					int dimens = 120;
					float density = getResources().getDisplayMetrics().density;
					int finalDimens = (int) (dimens * density);

					LinearLayout.LayoutParams imgvwDimens = new LinearLayout.LayoutParams(
							finalDimens, (int) (finalDimens * 1.5));
					imageView.setLayoutParams(imgvwDimens);

					ImageLoader.getInstance().displayImage(
							VMConst.URL + scene.getImageUrl(), imageView,
							MyDisplayImageOptions.getInstance());

					layout.addView(imageView);

				}

			}
		}
	};

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	protected void lazyLoad() {

		if (!isPrepared || !isVisible || mHasLoadedOnce) {
			return;
		}

		new AsyncTask<Void, Void, Boolean>() {

			@Override
			protected void onPreExecute() {
				super.onPreExecute();
				// 显示加载进度对话框
				// UIHelper.showDialogForLoading(getActivity(), "正在加载...",
				// true);
			}

			@Override
			protected Boolean doInBackground(Void... params) {
				try {

					Thread.sleep(300);
					init();
					downHandler.post(initData);
					// initData1();
					// 在这里添加调用接口获取数据的代码
					// doSomething()
				} catch (Exception e) {
					e.printStackTrace();
					Log.i(TAG, e.getMessage());
				}
				return true;
			}

			@Override
			protected void onPostExecute(Boolean isSuccess) {
				if (isSuccess) {
					// 加载成功
					init();
					mHasLoadedOnce = true;
				} else {
					// 加载失败
				}
				// 关闭对话框
				// UIHelper.hideDialogForLoading();
			}
		}.execute();

	}

}
